import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardBody,
  Flex,
  Heading,
  IconButton,
  SimpleGrid,
  Text,
  useColorModeValue,
  useDisclosure,
} from '@chakra-ui/react';
import { FaStar, FaRegStar, FaChevronLeft, FaChevronRight } from 'react-icons/fa';
import WordCard from '../components/vocabulary/word-card';
import WordDetailModal from '../components/vocabulary/word-detail-modal';
import wordsData from '../data/words.json';
import { Word } from '../types';

const Vocabulary: React.FC = () => {
  const [words, setWords] = useState<Word[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [favorites, setFavorites] = useState<Set<number>>(new Set());
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [selectedWord, setSelectedWord] = useState<Word | null>(null);
  const cardBg = useColorModeValue('white', 'gray.700');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  useEffect(() => {
    setWords(wordsData as Word[]);
    // Load favorites from localStorage
    const savedFavorites = localStorage.getItem('lingoLearnFavorites');
    if (savedFavorites) {
      setFavorites(new Set(JSON.parse(savedFavorites) as number[]));
    }
  }, []);

  const handlePrev = () => {
    setCurrentIndex(prev => (prev > 0 ? prev - 1 : words.length - 1));
  };

  const handleNext = () => {
    setCurrentIndex(prev => (prev < words.length - 1 ? prev + 1 : 0));
  };

  const toggleFavorite = (wordId: number) => {
    const newFavorites = new Set(favorites);
    if (newFavorites.has(wordId)) {
      newFavorites.delete(wordId);
    } else {
      newFavorites.add(wordId);
    }
    setFavorites(newFavorites);
    // Save to localStorage
    localStorage.setItem('lingoLearnFavorites', JSON.stringify([...newFavorites]));
  };

  const playAudio = (word: string) => {
    // In a real app, this would play actual audio
    // This is a placeholder function
  };

  const handleWordDetail = (word: Word) => {
    setSelectedWord(word);
    onOpen();
  };

  if (words.length === 0) {
    return (
      <Box textAlign="center" py={10}>
        <Text>Loading vocabulary...</Text>
      </Box>
    );
  }

  const currentWord = words[currentIndex];

  return (
    <Box maxW="container.md" mx="auto">
      <Flex justifyContent="space-between" alignItems="center" mb={6}>
        <Heading as="h2" size="lg">
          Vocabulary
        </Heading>
        <Text fontSize="sm" color="gray.500">
          {currentIndex + 1} / {words.length}
        </Text>
      </Flex>

      <Flex justifyContent="center" mb={6}>
        <IconButton
          icon={<FaChevronLeft />}
          onClick={handlePrev}
          aria-label="Previous word"
          size="lg"
          mx={2}
        />

        <Box flex="1" maxW="md" mx={4}>
          <WordCard
            word={currentWord}
            isFavorite={favorites.has(currentWord.id)}
            onToggleFavorite={() => toggleFavorite(currentWord.id)}
            onPlayAudio={() => playAudio(currentWord.word)}
            onShowDetail={() => handleWordDetail(currentWord)}
          />
        </Box>

        <IconButton
          icon={<FaChevronRight />}
          onClick={handleNext}
          aria-label="Next word"
          size="lg"
          mx={2}
        />
      </Flex>

      <Box mt={8}>
        <Heading as="h3" size="md" mb={4}>
          All Words
        </Heading>
        <SimpleGrid columns={{ base: 2, md: 3 }} spacing={4}>
          {words.map((word, index) => (
            <Card
              key={word.id}
              bg={cardBg}
              border="1px"
              borderColor={borderColor}
              cursor="pointer"
              onClick={() => setCurrentIndex(index)}
              boxShadow={currentIndex === index ? 'outline' : 'sm'}
            >
              <CardBody>
                <Flex justifyContent="space-between" alignItems="center">
                  <Text fontWeight="bold">{word.word}</Text>
                  <IconButton
                    icon={favorites.has(word.id) ? <FaStar /> : <FaRegStar />}
                    aria-label={
                      favorites.has(word.id) ? 'Remove from favorites' : 'Add to favorites'
                    }
                    size="sm"
                    variant="ghost"
                    onClick={e => {
                      e.stopPropagation();
                      toggleFavorite(word.id);
                    }}
                  />
                </Flex>
                <Text fontSize="sm" color="gray.500" mt={1}>
                  {word.translation}
                </Text>
              </CardBody>
            </Card>
          ))}
        </SimpleGrid>
      </Box>

      <WordDetailModal
        isOpen={isOpen}
        onClose={onClose}
        word={selectedWord}
        isFavorite={selectedWord ? favorites.has(selectedWord.id) : false}
        onToggleFavorite={selectedWord ? () => toggleFavorite(selectedWord.id) : () => {}}
      />
    </Box>
  );
};

export default Vocabulary;
